/**
 * Create Optimized files for distribution Optimized Task
 * @Author: jiangcheng198745@hotmail.com
 * @Date: 2015/07/09
 */
'use strict';

import gulp from 'gulp';
import runSeq from 'run-sequence';
import useref from 'gulp-useref';
import filter from 'gulp-filter';
import plumber from 'gulp-plumber';
import minifyCss from 'gulp-minify-css';
import uglify from 'gulp-uglify';
import rev from 'gulp-rev';
import revReplace from 'gulp-rev-replace';
import {log, colors} from 'gulp-util';


import config from '../gulp.config';
import messageLogger from '../utils/message.gulp';

gulp.task('optimize', (done) => {
    runSeq(
        [
            'optimize:app'
        ], 
        done
    );
});

gulp.task('optimize:app', () => {
    messageLogger('Optimized the Javascript, css and html for production index.html');

    let assets = useref.assets({
        searchPath:config.build
    });

    let cssFilter = filter('**/*.css', {
         restore: true
     });

    let jsFilter = filter('**/*.js', {
        restore: true
    })

    return gulp.src(config.build + '/index.html')
        .pipe(plumber(function (error) {
            log(colors.red(error));
        }))
        .pipe(assets)
        .pipe(cssFilter)
        // todo add concat plugin
        .pipe(minifyCss({
            restructuring: false
        }))
        .pipe(cssFilter.restore)
        .pipe(jsFilter)
        .pipe(uglify())
        .pipe(jsFilter.restore)
        .pipe(rev())
        .pipe(assets.restore())
        .pipe(useref())
        .pipe(revReplace())
        .pipe(gulp.dest(config.dist));

});